<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
            <el-form-item label="所属分类：" prop="category_id" width="150px">
                <treeselect style="width: 150px;" v-model="queryParams.category_id" :options="categoryOptions" :normalizer="normalizer" placeholder="选择上级分类" />
            </el-form-item>
            <el-form-item label="检查项名称" prop="search">
                <el-input
                    v-model="queryParams.search"
                    placeholder="请输入检查项名称"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>

            <el-form-item label="状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="状态" clearable>
                    <el-option
                        v-for="dict in dict.type.sys_normal_disable"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                >新增</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <el-table  v-loading="loading" :data="checkItemLists" border fit highlight-current-row>
            <el-table-column type="selection" width="55" bo align="center" label-width="100px" />
            <el-table-column label="id" align="center" prop="item_id"  width="50"/>
            <el-table-column label="所属分类" align="center" prop="apparatus_id" >
                <template slot-scope="{row}">
                    {{ row.category_info? row.category_info.category_name : "" }}
                </template>
            </el-table-column>
            <el-table-column label="检查项名称" align="center" prop="item_name" :show-overflow-tooltip="true" />
            <el-table-column label="检查项编号" align="center" prop="item_code"  />
            <el-table-column label="检测类型" align="center" prop="check_type"  />
            <el-table-column label="选项配置" width="200">
                <template slot-scope="{ row }">
                    <div v-if="row.check_type === 'enum'">
                        <el-tag
                            v-for="(opt, index) in enumOptionsItem(row)"
                            :key="index"
                            size="small"
                            class="mr-2"
                        >{{ opt }}
                        </el-tag>
                    </div>
                    <span v-else class="text-gray-400">N/A</span>
                </template>
            </el-table-column>
            <el-table-column label="标准值配置" min-width="220">
                <template slot-scope="{ row }">
                    <template v-if="row.standard_value">
                        <!-- 数值型 -->
                        <div v-if="row.check_type === 'number'">
                            范围: {{enumOptionsItem(row)}}
                            <el-tag v-if="row.data_unit" size="small">
                                {{ row.data_unit }}
                            </el-tag>
                        </div>

                        <!-- 布尔型 -->
                        <div v-if="row.check_type === 'bool'">
                            期望值:
                            <el-switch
                                :model-value="row.standard_value.expected_value"
                                inline-prompt
                                active-text="是"
                                inactive-text="否"
                                disabled
                            />
                        </div>
                        <!-- 文本型 -->
                        <div v-if="row.check_type === 'text'">
                            最大长度: {{ row.standard_value.max_length || '无限制' }}
                        </div>
                    </template>
                    <span v-else class="text-gray-400">未配置</span>
                </template>
            </el-table-column>
            <el-table-column prop="status" align="center" label="类型" width="100">
                <template slot-scope="{row}">
                    <dict-tag :options="dict.type.sys_normal_disable" :value="row.status"/>
                </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remark" />
            <el-table-column label="创建时间" align="center" prop="created_time"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
                <template slot-scope="{row}">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(row)"
                    >修改</el-button>
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(row)"
                    >删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.page"
            :limit.sync="queryParams.limit"
            @pagination="getList"
        />

        <!-- 添加或修改部门对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="所属分类：" prop="category_id">
                 <treeselect v-model="form.category_id" :options="categoryOptions" :normalizer="normalizer" placeholder="选择上级分类" />
                </el-form-item>
                <el-form-item label="检查项编码" prop="item_code">
                    <el-input v-model="form.item_code" placeholder="请输入检查项编码" />
                </el-form-item>
                <el-form-item label="检查项名称" prop="item_name">
                    <el-input v-model="form.item_name" placeholder="请输入检查项名称" />
                </el-form-item>
                <el-form-item label="检测类型" prop="check_type">
                    <el-radio-group v-model="form.check_type" @change="handleTypeChange">
                        <el-radio-button label="bool">布尔型</el-radio-button>
                        <el-radio-button label="number">数值型</el-radio-button>
                        <el-radio-button label="enum">枚举型</el-radio-button>
                        <el-radio-button label="text">文本型</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <!-- 动态配置区域 -->
                <div class="config-section">

                    <!-- 枚举选项配置 -->
                    <template v-if="form.check_type === 'enum'">
                        <div class="options-editor">
                            <h4>枚举选项配置</h4>
                            <el-tag v-for="(option, index) in enumOptions"  class="input-newtag"  :key="index" closable @close="removeOption(index)">
                                {{ option }}
                            </el-tag>
                            <el-input v-model="newOptionInput" class="input-new-tag" placeholder="输入选项后回车" @keyup.enter.native="addOption"/>
                        </div>
                    </template>

                    <!-- 数值型配置 -->
                    <template v-if="form.check_type === 'number'">
                        <el-form-item label="数值范围">
                            <el-input-number v-model="form.standard_value.min" placeholder="最小值" :precision="2"/>
                            <span class="range-separator">-</span>
                            <el-input-number v-model="form.standard_value.max" placeholder="最大值" :precision="2"/>
                        </el-form-item>

                        <el-form-item label="数据单位">
                            <el-select v-model="form.data_unit" placeholder="选择单位" clearable>
                                <el-option v-for="unit in dict.type.sys_check_item" :key="unit.label" :label="unit.label" :value="unit.label"/>
                            </el-select>
                        </el-form-item>
                    </template>
                    <!-- 标准值配置 -->
                    <el-form-item label="标准值配置" v-if="showStandardConfig">
                        <json-editor v-model="form.standard_value" :mode="'code'" class="json-editor"/>
                    </el-form-item>
                </div>

                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="form.status">
                        <el-radio
                            v-for="dict in dict.type.sys_normal_disable"
                            :key="dict.value"
                            :label="dict.value"
                        >{{dict.label}}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>

import {getCheckCategorySelectList} from "@/api/property/check/category";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import JsonEditor from '@/components/JsonEditor/index'
import {
    getApparatusAllList,
} from "@/api/grzq/apparatus.js";

import {getCheckItemList,createCheckItem,updateCheckItem,getCheckItemDetail,changeFiledStatus,delCheckItem} from "@/api/property/check/item";

export default {
    name: "master_read",
    dicts: ['sys_normal_disable','sys_check_item'],
    components: { Treeselect ,JsonEditor},
    data() {
        return {
            enumOptions:[],
            newOptionInput:"",
            showStandardConfig:false,
            // 遮罩层
            loading: true,
            loadingRead: true,
            // 显示搜索条件
            showSearch: true,
            // 表格数据
            categoryOptions: [],
            checkItemLists: [],
            total: 0,
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 重新渲染表格状态
            refreshTable: true,
            // 查询参数
            queryParams: {
                search: undefined,
                category_id: undefined,
                status: undefined,
                page: 1,
                limit: 10,
            },
            queryParamsRead: {
                item_id: undefined,
                page: 1,
                limit: 10,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                category_id: [
                    { required: true, message: "请选择片区", trigger: "blur" }
                ],
                item_name: [
                    { required: true, message: "检查项名称不能为空", trigger: "blur" }
                ],
                item_code: [
                    { required: true, message: "检查项编号不能为空", trigger: "blur" }
                ],
            },
        };
    },
    computed:{

    },
    created() {
        this.getList();
        this.getCategory();
    },
    methods: {
        standardValueItem(row){
            return JSON.parse(row.standard_value);
        },
        enumOptionsItem(row){
            console.log("row",row)
            if (row.check_type=='number'){
                let standard_value= JSON.parse(row.standard_value);
                return  standard_value.min +'~' + standard_value.max
            }else if (row.check_type='enum'){
                return JSON.parse(row.options);
            }else if (row.check_type='enum'){
                return JSON.parse(row.options);
            }
        },
        /** 查询部门列表 */
        async getList() {
            let that = this;
            that.loading = true;
            const {data, status, msg} = await getCheckItemList(this.queryParams);
            that.checkItemLists = data.data;
            that.loading = false;
            that.total = data.total;
            that.queryParams.limit = data.per_page || 10;

        },
        removeOption(index){
            this.enumOptions.splice(index, 1)
            this.form.options = [...this.enumOptions]
        },
        addOption(){
            console.log("---------------------")
            console.log("newOptionInput",this.newOptionInput)
            if (this.newOptionInput) {
                this.enumOptions.push(this.newOptionInput)
                this.form.options = [... this.enumOptions]
                console.log("enumOptions",this.enumOptions)
                console.log("options",this.options)
                this.newOptionInput = ''
            }
        },
        //片区
        async getCategory() {
            const response = await getCheckCategorySelectList();
            this.categoryOptions = this.handleTree(response.data, "category_id");
        },
        /** 转换分类数据结构 */
        normalizer(node) {
            if (node.children && !node.children.length) {
                delete node.children;
            }
            return {
                id: node.category_id,
                label: node.category_name,
                children: node.children
            };
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                item_id: undefined,
                category_id: undefined,
                item_name: undefined,
                item_code: undefined,
                check_type: undefined,
                standard_value: {},
                options: [],
                data_unit: undefined,
                remark: undefined,
                status: "1"
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 新增按钮操作 */
        handleAdd(row) {
            this.reset();
            this.enumOptions=[];
            this.open = true;
            this.title = "添加数据";
            this.form.dictType = this.queryParams.dictType;
        },
        handleTypeChange(type){
            this.form.standard_value = {}
            this.form.options = []
            if (type === 'enum') {
                this.form.options = []
            }
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            let that = this;
            this.reset();
            that.enumOptions=[];
            const item_id = row.item_id || this.ids
            getCheckItemDetail({item_id:item_id}).then(response => {
                let data= response.data;
                that.form = data;
                that.form.status = data.status.toString();
                that.form.standard_value = JSON.parse(data.standard_value);
                that.form.options = JSON.parse(data.options)
                console.log("this.form",this.form)
                that.enumOptions = data.options
                console.log("this.enumOptions",that.enumOptions)
                console.log("this.form",that.form)
                that.open = true;
                that.title = "修改";
            });
        },

        /** 提交按钮 */
        submitForm: function() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    this.form.standard_value=JSON.stringify(this.form.standard_value)
                    this.form.options=JSON.stringify(this.form.options)
                    if (this.form.item_id != undefined) {
                        updateCheckItem(this.form).then(response => {
                            this.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        createCheckItem(this.form).then(response => {
                            this.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            this.confirm('是否确认删除名称为"' + row.item_name + '"的数据项？').then(function() {
                return delCheckItem({item_id:row.item_id});
            }).then(() => {
                this.getList();
                this.msgSuccess("删除成功");
            }).catch(() => {});
        }
    }
};
</script>

<style lang="scss" scoped>
.options-editor {
    margin-bottom: 20px;
}
.data-add-container {
    padding: 24px;
    background: #fff;
    border-radius: 8px;
}

.config-section {
    border-left: 1px solid #eee;
    padding-left: 24px;
    min-height: 100px;
}
.input-newtag{
    margin: 10px;
}
.input-new-tag {
    width: 150px;
    margin-top: 10px;
}

.json-editor {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    height: 100px;
}

.range-separator {
    margin: 0 10px;
    color: #999;
}

.form-footer {
    margin-top: 24px;
    text-align: center;
}

.data-preview {
    margin-top: 30px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 4px;
}

</style>
